<?php

/**
 * @Author:             wuchenge
 * @Date:               2025-03-04 15:18:21
 * @Last Modified by:   wuchenge
 */
namespace App\Front\Controllers;

use App\Http\Controllers\ApiController;
use App\Libraries\JwtToken;
use App\Models\User;
use App\Requests\UserLoginRequest;
use App\Transformer\UserTransformer;
use Illuminate\Http\Request;

class LoginController extends ApiController
{
    /**
     * @var mixed
     */
    protected $user_transformer;

    /**
     * @param UserTransformer $user_transformer
     */
    public function __construct(UserTransformer $user_transformer)
    {
        $this->user_transformer = $user_transformer;
    }

    /**
     * @return mixed
     */
    public function refresh(Request $request)
    {
        $user = User::getWithInfoById($request->get('user')->id);

        $payload = [
            'id' => $user->id,
        ];

        $data = [
            'token' => JwtToken::createToken($payload),
            'user'  => $this->user_transformer->transform($user),
        ];

        return $this->response($data);
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function login(UserLoginRequest $request)
    {
        $email    = $request->input('email');
        $password = $request->input('password');
        $user     = User::getUserByEmail($email);
        if (!$user) {
            return $this->failed('邮箱不对');
        }

        if ($user->status == User::STATUS_NO) {
            return $this->failed('该用户被禁用');
        }

        if ($user->pwd != User::encodePassword($password)) {
            return $this->failed('密码不对');
        }

        // 要info信息
        $user = User::getWithInfoById($user->id);

        $payload = [
            'id' => $user->id,
        ];

        $data = [
            'token' => JwtToken::createToken($payload),
            'user'  => $this->user_transformer->transform($user),
        ];

        return $this->response($data);
    }

    /**
     * @param UserLoginRequest $request
     * @return mixed
     */
    public function register(UserLoginRequest $request)
    {
        $email = $request->input('email');
        $has   = User::getUserByEmail($email);
        if ($has) {
            return $this->failed('邮箱已被注册');
        }

        $password    = $request->input('password');
        $invite_code = $request->input('invite_code');
        $user        = User::register($email, $password, $invite_code);
        // 要info信息
        $user = User::getWithInfoById($user->id);

        $payload = [
            'id' => $user->id,
        ];

        $data = [
            'token' => JwtToken::createToken($payload),
            'user'  => $this->user_transformer->transform($user),
        ];

        return $this->response($data);
    }
}
